import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';

import 'package:wangziyi/db/address_dao.dart';
import 'package:wangziyi/entity/areas.dart';
import 'package:wangziyi/entity/cities.dart';

import 'package:wangziyi/entity/provinces.dart';
import 'package:wangziyi/entity/streets.dart';
import 'package:wangziyi/entity/user_address.dart';
import 'package:wangziyi/main.dart';

import 'package:flutter/services.dart';

class AddAddress extends StatefulWidget {
  @override
  _AddAddressState createState() => _AddAddressState();
}

class _AddAddressState extends State<AddAddress>
    with SingleTickerProviderStateMixin {
  //收货人名
  TextEditingController _addressUserName = TextEditingController();

//  电话
  TextEditingController _addressUserPhone = TextEditingController();

//  地区
  TextEditingController _addressUserAddress = TextEditingController();

//  详细地址
  TextEditingController _addressUserDetailedAddress = TextEditingController();

  FocusNode focusNode = FocusNode();
  TabController _tabController; //需要定义一个Controller

  var areas = List();
  List<String> names = List();
  List<String> code = List();

  // List<Province> listProvince = List();
  List<Provinces> listProvinces = List();
  List<Streets> listStreet = List();
  List<Areas> listAreas = List();
  List<Cities> listCities = List();
  List titles = [
    '收货姓名',
    '手机号码',
    '选择地区',
    '详细地址',
  ];
  List titleSubTitles = [
    '名字',
    '手机号',
    '省、市、区、街道',
    '小区楼栋/乡村名称',
  ];
  String provinceName = ""; //省
  String citieName = ""; //市
  String areaName = ""; //县
  String streetsName = ""; //街道

  int _currentProvicesIndex = 0;
  int _currentCitiesIndex = 0;
  int _currentAreasIndex = 0;
  int _currentStreetsIndex = 0;
  int _onIndex = -1;
  int _conut = 0;
  List tabBarTitles = ["中国大陆", "海外国家/地区"];
  String _errorText;

  bool isBool = true;
  int indexFocusNode = 0;
  GlobalKey globalKeys = GlobalKey();

  double containerWidth;
  double containerHeight;

  void _getWH() {
    containerWidth = globalKeys.currentContext.size.width;
    containerHeight = globalKeys.currentContext.size.height;
    print('Container widht is $containerWidth, height is $containerHeight');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _tabController = TabController(length: tabBarTitles.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加收货地址'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Container(
            child: ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int indexs) {
                  return Container(
                    margin: EdgeInsets.only(left: 10, right: 10),
                    child: TextField(
                      controller: _controller(indexs),
                      // enableInteractiveSelection: false,
                      style: TextStyle(fontWeight: FontWeight.w900),
                      textAlign: TextAlign.start,
                      maxLines: 1,
                      //最大行数
                      //能输入的最大字符个数
                      maxLength: indexs == 1 ? 11 : null,
                      //手机号个数
                      maxLengthEnforced: true,
                      //在达到最大长度时是否阻止输入
                      keyboardType: indexs == 1
                          ? TextInputType.phone
                          : TextInputType.text,
                      //设置输入类型
                      inputFormatters: [_inputFormatters(indexs)],
                      //输入框是否可用
                      // enabled: index==2?false:true,
                      //点击事件
                      onTap: () {
                        if (indexs == 2) {
                          FocusScope.of(context)
                              .requestFocus(new FocusNode()); //点击不可输入类容，失去焦点
                          //TODO 底部弹窗
                          return showModalBottomSheet(
                              isScrollControlled: true,
                              // barrierColor: Colors.red,
                              //设置圆角
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(20),
                                      topRight: Radius.circular(20))),
                              context: context,
                              builder: (context) {
                                return StatefulBuilder(
                                  builder: (context, setBottomSheetState) {
                                    return SizedBox(
                                      height: Get.size.height * 3 / 4,
                                      child: Scaffold(
                                        backgroundColor: Colors.transparent,
                                        appBar: PreferredSize(
                                          //设置APPbar的高度
                                          preferredSize: Size.fromHeight(
                                              containerHeight != null
                                                  ? containerHeight
                                                  : 100),
                                          child: AppBar(
                                            actions: <Widget>[
                                              IconButton(
                                                  icon: Icon(
                                                    Icons.cancel,
                                                    color: Colors.black54,
                                                    size: 30,
                                                  ),
                                                  onPressed: () =>
                                                      Navigator.pop(context))
                                            ],
                                            automaticallyImplyLeading: false,
                                            //去掉面前的返回键
                                            title: Text("请选择所在地区",style: TextStyle(color: Colors.black),),
                                            centerTitle: true,

                                            flexibleSpace: Container(
                                              // color: Colors.red,

                                              margin: EdgeInsets.only(
                                                  top: 50,
                                                  left: 20,
                                                  right: 20,
                                                  bottom: 50),
                                              child: Column(
                                                key: globalKeys,
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceAround,
                                                children: [
                                                  _addressSelectRow(
                                                      provinceName,
                                                      setBottomSheetState),
                                                  //选择的市
                                                  _addressSelectRow(citieName,
                                                      setBottomSheetState),
                                                  //选择的县、区
                                                  _addressSelectRow(areaName,
                                                      setBottomSheetState),
                                                  //街道
                                                  _addressSelectRow(streetsName,
                                                      setBottomSheetState),
                                                ],
                                              ),
                                            ),

                                            backgroundColor: Colors.transparent,
                                            elevation: 0,
                                            bottom: TabBar(
                                              controller: _tabController,
                                              tabs: tabBarTitles
                                                  .map((e) => Tab(
                                                        child: Text(
                                                          e,style: TextStyle(color: Colors.black),
                                                        ),
                                                      ))
                                                  .toList(),
                                            ),
                                          ),
                                        ),
                                        body: Column(
                                          children: [

                                            TabBarView(
                                              controller: _tabController,
                                              children: tabBarTitles.map((e) {
                                                if (e == '中国大陆') {
                                                  return FutureBuilder(
                                                      future: decodeProvince1(
                                                          'assets/json/pcas-code.json'),
                                                      builder: (
                                                        BuildContext context,
                                                        AsyncSnapshot sanpshot,
                                                      ) {
                                                        // listProvince = sanpshot.data;
                                                        listProvinces =
                                                            sanpshot.data;

                                                        if (sanpshot.hasData) {
                                                          //如果集合没有数据
                                                          if (names.length == 0) {
                                                            _initDataProvince();
                                                          }
                                                          return ListView.builder(
                                                            padding:
                                                                EdgeInsets.all(10),
                                                            itemBuilder:
                                                                (BuildContext
                                                                        context,
                                                                    int index) {
                                                              // if (index == 0) {
                                                              //   return Column(
                                                              //     crossAxisAlignment:
                                                              //     CrossAxisAlignment
                                                              //         .start,
                                                              //     children: <Widget>[
                                                              //       MyText(
                                                              //           provinceName,
                                                              //           Colors.grey,
                                                              //           16,
                                                              //           1),
                                                              //       // GridView.builder(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                                              //       //
                                                              //       // ), itemBuilder: (BuildContext context,int index){
                                                              //       //
                                                              //       // },itemCount: ,)
                                                              //     ],
                                                              //   );
                                                              // }
                                                              // index -= 1;

                                                              return ListTile(
                                                                  onTap: () {
                                                                    setBottomSheetState(
                                                                        () {
//记录点击次数
                                                                      _conut =
                                                                          _conut +
                                                                              1;
                                                                      print(_conut);
                                                                      //如果点击次数没有超过三次，就给Wieght添加高度
                                                                      if (_conut <
                                                                          3) {
                                                                        _getWH();
                                                                        //第一次要分配2个组件高度
                                                                        if (_conut ==
                                                                            0) {
                                                                          containerHeight =
                                                                              containerHeight / 2 +
                                                                                  200;
                                                                        } else if (_conut ==
                                                                            1) {
                                                                          containerHeight =
                                                                              containerHeight / 3 +
                                                                                  200;
                                                                        } else if (_conut ==
                                                                            2) {
                                                                          containerHeight =
                                                                              containerHeight / 4 +
                                                                                  200;
                                                                        }

                                                                        // print(containerHeight);
                                                                      }

                                                                      if (listProvinces
                                                                              .length ==
                                                                          names
                                                                              .length) {
                                                                        // print("city_code:${listProvinces.length}==${names.length}");
                                                                        streetsName =
                                                                            '请选择城市';
                                                                        areaName =
                                                                            "";
                                                                        //选择市给下标0
                                                                        _onIndex =
                                                                            1;
                                                                        //展示选择的市
                                                                        provinceName =
                                                                            names[
                                                                                index];
                                                                        //记住点击省份的下标
                                                                        _currentProvicesIndex =
                                                                            index;

                                                                        listCities =
                                                                            listProvinces[index]
                                                                                .children;
                                                                        //把市区遍历，添加到集合
                                                                        _getPCAS_Data(
                                                                            listCities);
                                                                      } else if (listProvinces[
                                                                                  _currentProvicesIndex]
                                                                              .children
                                                                              .length ==
                                                                          names
                                                                              .length) {
                                                                        areaName =
                                                                            '请先择县';
                                                                        streetsName =
                                                                            '';
                                                                        //选择县给下标县
                                                                        _onIndex =
                                                                            2;
                                                                        //展示选择的县
                                                                        citieName =
                                                                            names[
                                                                                index];
                                                                        //把县遍历，添加到集合

                                                                        listAreas = listProvinces[
                                                                                _currentProvicesIndex]
                                                                            .children[
                                                                                index]
                                                                            .children;
                                                                        _getPCAS_Data(
                                                                            listAreas);
                                                                        //记住点击市区的下标
                                                                        _currentCitiesIndex =
                                                                            index;
                                                                      } else if (listProvinces[
                                                                                  _currentProvicesIndex]
                                                                              .children[
                                                                                  _currentCitiesIndex]
                                                                              .children
                                                                              .length ==
                                                                          names
                                                                              .length) {
                                                                        streetsName =
                                                                            '请选择街道';
                                                                        //选择街道给下标。代表3
                                                                        _onIndex =
                                                                            3;
                                                                        //展示选择的街道
                                                                        areaName =
                                                                            names[
                                                                                index];
                                                                        //把街道遍历，添加到集合
                                                                        listStreet = listProvinces[_currentProvicesIndex]
                                                                            .children[
                                                                                _currentCitiesIndex]
                                                                            .children[
                                                                                index]
                                                                            .children;
                                                                        _getPCAS_Data(
                                                                            listStreet);
                                                                        //记住点击县的下标
                                                                        _currentAreasIndex =
                                                                            index;
                                                                      } else
                                                                      // if(listProvinces[_currentProvicesIndex].children[_currentCitiesIndex].children[_currentAreasIndex].children[index].name==names[index]
                                                                      //     &&listProvinces[_currentProvicesIndex].children[_currentCitiesIndex].children[_currentAreasIndex].children[index].code==code[index]
                                                                      // &&listProvinces[_currentProvicesIndex].children[_currentCitiesIndex].children[_currentAreasIndex].children.length==names.length
                                                                      // )
                                                                      {
                                                                        print(names
                                                                            .length);
                                                                        print(listProvinces[_currentProvicesIndex]
                                                                            .children[
                                                                                _currentCitiesIndex]
                                                                            .children[
                                                                                _currentAreasIndex]
                                                                            .children
                                                                            .length);

                                                                        _onIndex =
                                                                            4;
                                                                        streetsName =
                                                                            names[
                                                                                index];

                                                                        //记录街道下标
                                                                        _currentStreetsIndex =
                                                                            index;

                                                                        // Navigator.pop(context);
                                                                      }
                                                                    });
                                                                  },
                                                                  leading: text(
                                                                      index,
                                                                      item(
                                                                          index,
                                                                          names[
                                                                              index])),
                                                                  title: text(
                                                                      index,
                                                                      names[
                                                                          index]));
                                                            },
                                                            itemCount: names.length,
                                                          );
                                                        }
                                                        return Container(
                                                            child: Text("数据异常"));
                                                      });
                                                } else {
                                                  return Container(
                                                    child: Text(
                                                      e,
                                                      textScaleFactor: 1,
                                                    ),
                                                  );
                                                }
                                              }).toList(),
                                            ),
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                );
                              });
                        } else {}
                      },
                      decoration: InputDecoration(
                          counterText: "",
                          //取消右小角计数器
                          contentPadding: EdgeInsets.symmetric(vertical: 23),
                          //输入框整体高度
                          //错误文本
                          errorText: indexs == 0 ? _errorText : null,
                          errorStyle: TextStyle(fontWeight: FontWeight.w900),

                          // errorMaxLines: 1,
                          hintText: _hinText(indexs),
                          //提示类容
                          hintStyle: _hinTextStyle(indexs),
                          // border: InputBorder.none //去除下划线
                          prefixIcon: Container(
                              padding: EdgeInsets.symmetric(vertical: 23),
                              margin: EdgeInsets.only(right: 20),
                              child: Text(titles[indexs])),
                          suffixIcon: _suffixIcons(indexs),
                          enabledBorder:
                              _underlineInputBorder(1, Color(0xffdedede)),
                          //输入框可用时显示的边框，如果errorText不为空的话，该属性无效
                          focusedBorder:
                              _underlineInputBorder(1, Color(0xffdedede)),
                          //输入框有焦点时的边框,如果errorText不为空的话，该属性无效
                          focusedErrorBorder:
                              _underlineInputBorder(1, Color(0xffdedede)),
                          //errorText不为空时，输入框有焦点时的边框
                          errorBorder: _underlineInputBorder(1,
                              Color(0xffdedede)) //errorText不为空，输入框没有焦点时要显示的边框
                          ),

                      onChanged: (value) {
                        setState(() {
                          if (value.length > 25) {
                            _errorText = "收货人长度需要在1-25个汉字或字符之间,不能包含特殊字符";
                          } else {
                            _errorText = null;
                          }
                        });
                      },
                    ),
                  );
                },
                itemCount: titles.length),
          ),
          GestureDetector(
            child: Container(
              width: double.maxFinite,
              margin: EdgeInsets.only(top: 10, left: 20, right: 20),
              child: MaterialButton(
                shape: RoundedRectangleBorder(
                    side: BorderSide.none,
                    borderRadius: BorderRadius.circular(50)),
                height: 50,
                child: Text("保存"),
                color: Colors.deepOrange,
                onPressed: () {
                  print(_addressUserName.text);
                  print(_addressUserPhone.text);
                  print("$provinceName+$streetsName+$areaName");
                  print(_addressUserDetailedAddress.text);
                  if (_addressUserName.text.isEmpty ||
                      _addressUserName.text.length > 25) {
                    rerrorDialog("收货人长度需要在1-25个汉字或字符之间，不能包含特殊字符");
                  } else if (_addressUserPhone.text.isEmpty ||
                      _addressUserPhone.text.length < 11) {
                    rerrorDialog("请输入正确的手机号码");
                  } else if (provinceName == "" && streetsName == "" ||
                      streetsName == '请选择城市' && areaName == "" ||
                      areaName == '请选择县') {
                    rerrorDialog("请选择完整的行政区");
                  } else if (_addressUserDetailedAddress.text.isEmpty ||
                      _addressUserDetailedAddress.text.length > 120 ||
                      _addressUserDetailedAddress.text.length < 2) {
                    rerrorDialog("详细地址长度需要在2-120个字符之间,不能包含特殊字符");
                  } else {
                    print("正确");

                    inserAddress();
                  }
                },
              ),
            ),
            onTap: () {},
          )
        ],
      ),
    );
  }

  _suffixIcons(index) {
    if (index == 0) {
      return _suffixIconsRow(Text('+通讯录'));
    } else if (index == 1) {
      return _suffixIconsRow(Text('+86'));
    } else if (index == 2) {
      return _suffixIconsRow(Text(""));
    }
  }

  _suffixIconsRow(Widget widget) {
    return Row(
        mainAxisAlignment: MainAxisAlignment.end, //对齐方式
        mainAxisSize: MainAxisSize.min, //自适应宽度

        children: <Widget>[
          widget,
          Icon(
            Icons.keyboard_arrow_right,
            color: Colors.grey,
          ),
        ]);
  }

  _inputFormatters(int index) {
    if (index == 1) {
      return FilteringTextInputFormatter.digitsOnly; //只允许输入数字
    } else {
      return FilteringTextInputFormatter.deny('"{}() \/*?:<>|'); //禁止输入非法字符
    }
  }

  _underlineInputBorder(double width, Color color) {
    return UnderlineInputBorder(
        borderSide: BorderSide(width: width, color: color //当没有获取焦点时 下划线的颜色
            ));
  }

//读取json文件
  Future<String> _loadCityInfoJson(String jsonName) async {
    return await rootBundle.loadString(jsonName);
  }

  // 将json字符串转对象
  Future<List<Provinces>> decodeProvince1(String jsonName) async {
    //读取本地的json字符串
    String provinceJson = await _loadCityInfoJson(jsonName);
    // 解析json字符串，返回Map
    List<dynamic> jsonMap = json.decode(provinceJson);
    // print(jsonMap);
    // print("===========");
    List<Provinces> listProvince =
        jsonMap.toList().map((e) => Provinces.fromJson(e)).toList();
    return listProvince;
  }

  item(index, str) {
    //取首字母拼音//capitalize()首字母大写
    String string = PinyinHelper.getFirstWordPinyin(str);
    // 取拼音第一个字母
    //无法转换拼音 默认用'#'替代
    // PinyinHelper.convertToPinyinStringWithoutException(string, separator: " ", defPinyin: '#', format: PinyinFormat.WITHOUT_TONE);//tian fu guang chang
    String stringIndex = string[0].toUpperCase(); //toUpperCase大写
    return stringIndex;
  }

  Widget text(index, String str) {
    return Container(
      child: Text(str),
    );
  }

  _hinText(indexs) {
    if (provinceName != "") {
      titleSubTitles[2] = provinceName;
      if (citieName != "" && citieName != "请选择城市") {
        titleSubTitles[2] = provinceName + "--" + citieName;
        if (areaName != "" && areaName != "请选择县") {
          titleSubTitles[2] = provinceName + "--" + citieName + "--" + areaName;
          if (streetsName != "" && streetsName != "请选择街道") {
            titleSubTitles[2] = provinceName +
                "--" +
                citieName +
                "--" +
                areaName +
                "--" +
                streetsName;
          }
        }
      }
    }
    return titleSubTitles[indexs];
  }

  _hinTextStyle(int indexs) {
    if (indexs == 2) {
      //任意一个有值就改变颜色
      if (provinceName != "" || streetsName != "" || areaName != "") {
        return TextStyle(color: Colors.black, fontWeight: FontWeight.w900);
      }
    }

    return TextStyle(color: Colors.grey, fontWeight: FontWeight.w900);
  }

  Color _cityColor(string) {
    // print("provinceName：$provinceName,streetsName:$streetsName,areaName：$areaName,");
    // print("string:$string");
    if (_onIndex == 0 && string == provinceName) {
      return Colors.deepOrange;
    } else if (_onIndex == 1 && string == citieName) {
      return Colors.deepOrange;
    } else if (_onIndex == 2 && string == areaName) {
      return Colors.deepOrange;
    } else if (_onIndex == 3 && string == streetsName) {
      return Colors.deepOrange;
    } else if (_onIndex == 4 && string == streetsName) {
      return Colors.deepOrange;
    } else if (_onIndex == 1 && string == '请选择城市') {
      return Colors.deepOrange;
    } else if (_onIndex == 2 && string == '请选择县') {
      return Colors.deepOrange;
    } else if (_onIndex == 3 && string == '请选择街道') {
      return Colors.deepOrange;
    } else
      return Colors.black;
  }

  Widget _addressSelectRow(String string, setBottomSheetState) {
    if (string != "") {
      return GestureDetector(
        child: Container(
            child: Row(
          //左右两边对其
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          // crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(string,style: TextStyle(color: _cityColor(string)),),
            Icon(Icons.keyboard_arrow_right)
          ],
        )),
        onTap: () {
          if (string == provinceName) {
            _onIndex = 0;

            setBottomSheetState(() {
              _getPCAS_Data(listProvinces);
            });

            _cityColor(string);
          } else if (string == citieName && string != "请选择城市") {
            _onIndex = 1;

            print(listCities.length);
            setBottomSheetState(() {
              _getPCAS_Data(listCities);
            });

            print(names.length);
            _cityColor(string);
          } else if (string == areaName && string != '请选择县') {
            _onIndex = 2;

            setBottomSheetState(() {
              _getPCAS_Data(listAreas);
            });

            _cityColor(string);
          } else if (string == streetsName && string != '请选择街道') {
            _onIndex = 3;
            setBottomSheetState(() {
              _getPCAS_Data(listStreet);
            });
            _cityColor(string);
          }
        },
      );
    } else {
      return Container(
        height: 0,
        width: 0,
      );
    }
  }

  void _onClick(int index) {
    print(index);
  }

  void _initDataProvince() {
    listProvinces.forEach((element) {
      names.add(element.name);
      code.add(element.code);
    });
  }

  _controller(indexs) {
    if (indexs == 0) {
      return _addressUserName;
    } else if (indexs == 1) {
      return _addressUserPhone;
    } else if (indexs == 2) {
      return _addressUserAddress;
    } else if (indexs == 3) {
      return _addressUserDetailedAddress;
    }
  }

  void rerrorDialog(rerroe) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: Text(rerroe),
            actions: <Widget>[
              FlatButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: Text("确定"))
            ],
          );
        });
  }

  // ,,provinceName,streetsName
  Future inserAddress() async {
    //初始化dao
    AddressDao dao = AddressDao();
    //插入数据
    UserAddress userAddress = UserAddress(_addressUserName.text,
        _addressUserPhone.text, provinceName, _addressUserDetailedAddress.text);
    int i = await dao.insert(userAddress);
    print("插入数据成功：$i");
  }

  void _getPCAS_Data(List children) {
    //清空集合
    names.clear();
    code.clear();
    children.forEach((element) {
      names.add(element.name);
      code.add(element.code);
    });
  }
}
